#[allow(unused)]
use std::{env, error::Error, fs};

#[derive(Debug, PartialEq)]
pub struct Config {
    pub query: String,
    pub filename: String,
    pub case_sensitive: bool,
}

impl Config {
    pub fn new(args: &[String]) -> Result<Config, &'static str> {
        if args.len() < 3 {
            return Err("not enough arguments");
        }

        let mut args = args.to_vec();

        let case_sensitive = if args[1].starts_with("-") {
            match args.remove(1).as_str() {
                "-i" => false,
                "-I" => true,
                _ => true, // 这里可以做成错误处理，或者识别其他传入的参数
            }
        } else {
            match env::var("CASE_INSENSITIVE") {
                // 当 CASE_INSENSITIVE=1 时才被认为是大小不敏感
                Ok(s) if s == 1.to_string() => false,
                _ => true,
            }
        };

        let query = args[1].clone();
        let filename = args[2].clone();

        Ok(Config {
            query,
            filename,
            case_sensitive,
        })
    }
}

pub fn run(config: Config) -> Result<(), Box<dyn Error>> {
    let contents = fs::read_to_string(&config.filename)?;

    // println!("\nWith text:\n{}", contents);

    let find = if config.case_sensitive {
        search(&config.query, &contents)
    } else {
        search_case_insensitive(&config.query, &contents)
    };

    for line in find {
        println!("{}", line);
    }

    Ok(())
}

pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
    let mut find: Vec<&str> = Vec::new();

    for line in contents.lines() {
        if line.contains(query) {
            find.push(line);
        }
    }

    find
}

pub fn search_case_insensitive<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
    let mut find: Vec<&str> = Vec::new();
    let query_lower = query.to_lowercase();

    for line in contents.lines() {
        if line.to_lowercase().contains(&query_lower) {
            find.push(line);
        }
    }

    find
}
